import { defineStore } from "pinia";
import axios from "axios";
import router from "../router/index";

export const useStore = defineStore("data", {
  state: () => {
    return {
      userInfo: {},
      exception: "" as string,
    };
  },
  actions: {
    async login(username: string, pwd: string) {
      try {
        const res = await axios.post("/login", {
          username: username,
          pwd: pwd,
        });

        if (res.data.code === 200) {
          //登录成功
          this.userInfo = { username: username, pwd: pwd };
          //将返回的token存入sessionStorage中
          sessionStorage.setItem("token", res.data.token);

          router.push("/index");
        }
      } catch (error) {
        //登录失败
        alert("登录失败，账号或者密码错误！");
        return error;
      }
    },
  },
});
